#include "BufferedReader.h"

#include "Exception.h"
#include "WinException.h"
#include "SocketException.h"

using namespace std;

BufferedReader::BufferedReader(IConnection& connection) 
	: _connection(connection) 
{
	printf(__FUNCTION__ "\n");
	printf( "Hier: %s\n",connection.toString().c_str());
}

string BufferedReader::readLine() {
	printf(__FUNCTION__ "\n");
	
	DWORD bytesRead=0;
	void* posNewline = NULL;
	char* buf;
	int BUFSIZE;

	int nlPos = mBuffer.find('\n');
	if (nlPos >= 0) {
		// there is a complete line in the already available buffer
		return mBuffer.decommit(nlPos+1);

	} else do {
		// there is no newline in the buffer
		// keep reading data until a Newline character arrives
		BUFSIZE = mBuffer.getBufferCapacity();
		buf = mBuffer.reserve(BUFSIZE);
		assert(BUFSIZE > 0);
		if (BUFSIZE == 0) throw Exception( "SerialConnection::readLine() : mBuffer.reserve() : There is no more Buffer space available in the BipBuffer");


		 bytesRead = _connection.read(buf, BUFSIZE);
	

		assert(bytesRead > 0);

		mBuffer.commit(bytesRead);

		// check the new bytes for a NL
		posNewline = memchr(buf, '\n',bytesRead);	

	} while (posNewline == NULL);
	
	int offset = bytesRead - ((int)posNewline - (int)buf + 1);
	int sizeToDecommit = mBuffer.getCommittedSize() - offset;

	return mBuffer.decommit(sizeToDecommit);;
}

